package cn.cuilan.controller;

import cn.cuilan.utils.FileUpload;
import cn.cuilan.utils.Results;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 公共文件上传
 *
 * @author zhang.yan
 */
@RestController
public class FileUploadController {

    /**
     * 保存文件路径
     */
    @Value("${xiaozhu.filePath}")
    private String filePath;

    /**
     * 文件上传
     *
     * @param file 文件
     * @return 返回成功，路径
     */
    @RequestMapping(value = "/api/upload", method = RequestMethod.POST)
    public Results fileUpload(@RequestParam(value = "file") MultipartFile file) {
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 绝对路径
        String absolutePath;
        try {
            absolutePath = FileUpload.saveLocalFile(file.getBytes(), filePath + "upload/", fileName);
        } catch (IOException e) {
            return Results.error().data("文件上传失败");
        }
        return Results.success().data("path", absolutePath);
    }

}
